package com.hui.servlet;

import com.hui.entity.User;
import com.hui.service.AdminService;
import com.hui.util.ServiceFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: 李昭辉
 * @Date: 2021/06/19/15:46
 * @Description: 管理员登入
 */
@WebServlet(name = "LoginServlet", urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    private AdminService adminService = ServiceFactory.getAdminService();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        User user = new User(username,password);
        boolean res = adminService.adminLogin(user);
        // 成功就跳转成功页面
        if (res) {
            //将用户名保存到 session 中
            req.getSession().setAttribute("name",username);
            // 转发pageStudent，获取学员数据
            req.getRequestDispatcher("pageStudent").forward(req, resp);
        } else {
            // 失败就返回原来页面
            req.setAttribute("error","登入失败，用户名或密码错误！！！");
            req.getRequestDispatcher("index.jsp").forward(req, resp);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}
